import { defineStore } from 'pinia'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:3001/api'

export const useUniversityStore = defineStore('university', {
  state: () => ({
    universities: [],
    universityOptions: [],
    loading: false,
    isLoading: false, // 保持兼容性
    error: null,
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    }
  }),

  getters: {
    allUniversities: (state) => state.universities,
    rawUniversities: (state) => state.universities,
    getUniversityById: (state) => (id) => state.universities.find(u => u._id === id)
  },

  actions: {
    async fetchUniversities(params = {}) {
      this.loading = true
      this.isLoading = true
      this.error = null
      try {
        const response = await axios.get(`${API_BASE_URL}/universities`, { params })
        const data = response.data.data || response.data
        this.universities = data.universities || data || []
        this.pagination = {
          page: data.currentPage || 1,
          limit: params.limit || this.pagination.limit,
          total: data.total || this.universities.length,
          totalPages: data.totalPages || Math.ceil((data.total || this.universities.length) / (params.limit || this.pagination.limit))
        }
        return this.universities
      } catch (err) {
        this.error = err.response?.data?.error || '获取高校列表失败'
        console.error('获取高校列表失败:', err)
        throw err
      } finally {
        this.loading = false
        this.isLoading = false
      }
    },

    async fetchUniversityOptions() {
      if (this.universityOptions.length > 0) return this.universityOptions
      this.isLoading = true
      this.error = null
      try {
        const response = await axios.get(`${API_BASE_URL}/universities/options`)
        const data = response.data.data || response.data
        this.universityOptions = data || []
        return this.universityOptions
      } catch (err) {
        this.error = err.response?.data?.error || '获取高校选项失败'
        console.error('获取高校选项失败:', err)
        throw err
      } finally {
        this.isLoading = false
      }
    },

    async addUniversity(universityData) {
      this.loading = true
      this.isLoading = true
      this.error = null
      try {
        const response = await axios.post(`${API_BASE_URL}/universities`, universityData)
        // 重新获取完整的高校列表以确保数据一致性
        await this.fetchUniversities()
        const data = response.data.data || response.data
        return data
      } catch (err) {
        this.error = err.response?.data?.error || '创建高校失败'
        console.error('创建高校失败:', err)
        throw err
      } finally {
        this.loading = false
        this.isLoading = false
      }
    },

    async updateUniversity(id, universityData) {
      this.loading = true
      this.isLoading = true
      this.error = null
      try {
        const response = await axios.put(`${API_BASE_URL}/universities/${id}`, universityData)
        // 重新获取完整的高校列表以确保数据一致性
        await this.fetchUniversities()
        const data = response.data.data || response.data
        return data
      } catch (err) {
        this.error = err.response?.data?.error || '更新高校信息失败'
        console.error('更新高校信息失败:', err)
        throw err
      } finally {
        this.loading = false
        this.isLoading = false
      }
    },

    async deleteUniversity(id) {
      this.loading = true
      this.isLoading = true
      this.error = null
      try {
        await axios.delete(`${API_BASE_URL}/universities/${id}`)
        // 重新获取完整的高校列表
        await this.fetchUniversities()
      } catch (err) {
        this.error = err.response?.data?.error || '删除高校失败'
        console.error('删除高校失败:', err)
        throw err
      } finally {
        this.loading = false
        this.isLoading = false
      }
    },

    // 导出高校信息到Excel
    async exportToExcel() {
      try {
        const response = await axios.get(`${API_BASE_URL}/export/universities`, {
          responseType: 'blob'
        })

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url

        // 从响应头获取文件名
        const contentDisposition = response.headers['content-disposition']
        let filename = `高校信息_${new Date().toISOString().split('T')[0]}.xlsx`
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename="(.+)"/)
          if (filenameMatch) {
            filename = decodeURIComponent(filenameMatch[1])
          }
        }

        link.download = filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        return true
      } catch (err) {
        console.error('导出高校信息失败:', err)
        throw err
      }
    }
  }
})

